from flask import Flask, request
import pymysql

APP = Flask(__name__)

@APP.route('/')
def hello_world():
	config = {
	    'host': '10.125.128.38',
	    'port': 3306,
	    'user': 'root',
	    'passwd': '!23CsmRjyjy',
	    'charset':'utf8mb4',
	    'cursorclass':pymysql.cursors.DictCursor
	    }
	conn = pymysql.connect(**config)
	conn.autocommit(1)
	cursor = conn.cursor()
	global rr
	rr = ''
	try:
	    # 创建数据库
	    DB_NAME = 'test'
	    #cursor.execute('DROP DATABASE IF EXISTS %s' %DB_NAME)
	    #cursor.execute('CREATE DATABASE IF NOT EXISTS %s' %DB_NAME)
	    conn.select_db(DB_NAME)

	    #创建表
	    TABLE_NAME = 'user'
	    #cursor.execute('CREATE TABLE %s(id int primary key,name varchar(30))' %TABLE_NAME)

	    # 批量插入纪录
	    values = []
	    #for i in range(20):
	    	#values.append((i,'kk'+str(i)))
	    ssql = 'INSERT INTO user (name) values(\'' + 's' + '\');';
	    sql2 = 'INSERT INTO user (name) values(\'%s\')' % ('ss');
	    print(sql2)
	    cursor.execute(sql2)

	    # 查%s询数据条目
	    count = cursor.execute('SELECT * FROM %s' %TABLE_NAME)
	    print('total records:', cursor.rowcount)

	    # 获取表名信息
	    desc = cursor.description

	    print (desc[0][0], desc[1][0])

	    cursor.scroll(2,mode='absolute')
	    results = cursor.fetchall()
	    for result in results:
	    	rr += str(result) + ','
	    	print (result)

	except:
	    import traceback
	    traceback.print_exc()
	    # 发生错误时会滚
	    conn.rollback()
	finally:
	    # 关闭游标连接
	    cursor.close()
	    # 关闭数据库连接
	    conn.close()
	return rr

@APP.route('/s')
def s():
   return 's'

@APP.route('/insert')
def insert():
	config = {
	    'host': '10.125.128.38',
	    'port': 3306,
	    'user': 'root',
	    'passwd': '!23CsmRjyjy',
	    'charset':'utf8mb4',
	    'cursorclass':pymysql.cursors.DictCursor
	    }
	conn = pymysql.connect(**config)
	conn.autocommit(1)
	cursor = conn.cursor()
	global rr
	rr = request.args.get("name")
	try:
		DB_NAME = 'test'
		conn.select_db(DB_NAME)
		sql2 = 'INSERT INTO user (name) values(\'%s\')' % (rr);
		cursor.execute(sql2)
	except:
	    import traceback
	    traceback.print_exc()
	    # 发生错误时会滚
	    conn.rollback()
	finally:
	    # 关闭游标连接
	    cursor.close()
	    # 关闭数据库连接
	    conn.close()
	return rr

if __name__ == '__main__':
   APP.run()